/*
 * @Description: 请求失败的统一返回结果
 * @Author: lihk
 * @Date: 2024-09-24 17:37:44
 */
import { Catch, ExceptionFilter, ArgumentsHost, HttpException, HttpStatus } from '@nestjs/common';
import { Response } from 'express';

@Catch()
export class GlobalExceptionFilter implements ExceptionFilter {
  catch(exception: any, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();

    let status = HttpStatus.INTERNAL_SERVER_ERROR;
    let message = 'Internal Server Error';

    if (exception instanceof HttpException) {
      status = exception.getStatus();
      message = this.getMessageByStatusCode(status);
    }
    console.log("🚀 ~ GlobalExceptionFilter ~ exception:", exception.response)

    response.status(status).json({
      code: status,
      msg: exception.response || message,
    });
  }

  private getMessageByStatusCode(statusCode: number): string {
    switch (statusCode) {
      case HttpStatus.OK:
        return '成功';
      case HttpStatus.BAD_REQUEST:
        return statusCode + '请求错误，请检查参数';
      case HttpStatus.UNAUTHORIZED:
        return statusCode + '未授权';
      case HttpStatus.FORBIDDEN:
        return statusCode + '当前禁止访问，请检查权限';
      case HttpStatus.NOT_FOUND:
        return statusCode + '未找到，请检查请求方法或请求路径';
      case HttpStatus.METHOD_NOT_ALLOWED:
        return statusCode + '方法不允许';
      default:
        return statusCode + '错误';
    }
  }
}